package basics.io;

import exercises.newcoder.util.ListNode;

import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.util.function.Consumer;

/**
 * @author or2
 * @Description 使用序列化深拷贝
 * @create 2021年09月15日 时间: 12:04
 */
public class SerializeClone {
    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        ListNode byIn = ListNode.getByIn("{1,2,3}");
        ListNode listNode = null;

        try (ByteArrayOutputStream out = new ByteArrayOutputStream();
             ObjectOutputStream objectOutputStream = new ObjectOutputStream(out)) {

            objectOutputStream.writeObject(byIn);
            ObjectInputStream objectInputStream = new ObjectInputStream(new ByteArrayInputStream(out.toByteArray()));
            listNode = (ListNode) objectInputStream.readObject();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }

        ListNode clone = byIn.clone();
//        Object类拷贝方式 - 无法通过反射?
        //Method method = Object.class.getDeclaredMethod("clone");
        //method.setAccessible(true);
        //Object cloneByObject = method.invoke(byIn);
        ListNode cloneByObject = byIn.badClone();
//        修改下一链表的值, 测试拷贝方式
        byIn.next.val = 4;

        Consumer<Integer> consumer = integer -> System.out.printf("%d\t", integer);
        byIn.foreach(consumer);
        System.out.println("———————— 原始链表");
        cloneByObject.foreach(consumer);
        System.out.println("———————— Object.clone");
        clone.foreach(consumer);
        System.out.println("———————— 覆写clone");
        listNode.foreach(consumer);
        System.out.println("———————— 序列化生成的");

    }
}
